#include <stdlib.h>
#include <string.h>

#include "GL/glut.h"
#include "PinnedObject.h"

PinnedObject::PinnedObject(TextureManager * textureManager, float textureRotation, Vertex position, VertexList * vertices, Material * material, float mass)
:ClosedObject(textureManager, textureRotation, position, vertices, material, mass)
{
}
PinnedObject::PinnedObject(TextureManager * textureManager, Vertex position)
:ClosedObject(textureManager, position)
{
}
PinnedObject::PinnedObject(TextureManager * textureManager, Vertex position, VertexList * vertices)
:ClosedObject(textureManager, position, vertices)
{
}
PinnedObject::~PinnedObject()
{
}
void PinnedObject::Draw()
{
	if(vertices)
		vertices->Draw();
	position.Draw();
	
	if(vertices &&  vertices->head && vertices->tail)
	{
		glBegin(GL_LINES);
		glVertex2f(vertices->head->payload->GetPosition().x, vertices->head->payload->GetPosition().y);
		glVertex2f(vertices->tail->payload->GetPosition().x, vertices->tail->payload->GetPosition().y);	
		glEnd();
	}
	
	//draw the closed shape
	
	if(textureIndex >= 0)
	{
		TexturedDraw();
	}
	else
	{
		if(activeObject)
			glColor4f(1.0,0.0,0.0,0.8);
		else
			glColor4f(1.0,0.0,0.0,0.4);
			
		glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
		glAlphaFunc( GL_GREATER, 0.01 );
		glEnable( GL_ALPHA_TEST );
		glEnable(GL_BLEND);
		glBegin(GL_POLYGON);
		
		List<Vertex> * search = vertices->head;
		while(search)
		{
			if(search->payload)
				glVertex2f(search->payload->GetPosition().x,search->payload->GetPosition().y);
			search = search->next;
		}
		glEnd();
	}
	glDisable(GL_BLEND);
}
char * PinnedObject::GetTag()
{
	printf("Getting border tag\n");
	char * points = vertices->GetRelativeTag(position.GetPosition());
	char * positionTag = position.GetTag();
	char * mass = propertyMenu->GetFormContent(0);
	char * tag = (char *)malloc(strlen(points)+strlen(positionTag)+strlen(material->name)+strlen(mass)+40);
	sprintf(tag, "<object,baseobject,%s,%.3f,%d,%s,%s,1,%s>",material->name, textureRotation,vertices->GetLength(),points,positionTag, mass);
	delete points;
	free(mass);
	return tag;	
}
